package org.lhg.activiti.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.lhg.activiti.mapper.NewsMapper;
import org.lhg.activiti.model.News;
import org.lhg.activiti.service.NewsService;
import org.lhg.activiti.util.ElUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Value("${news_apply}")
    private String news_apply;

    @Override
    public List<News> news_list(Map<String, Object> map) {
        return newsMapper.news_list(map);
    }

    @Override
    public Long new_list_total(Map<String, Object> map) {
        return newsMapper.new_list_total(map);
    }

    @Override
    public int news_add(News news) {
        //工作流
        Map<String,Object> variables=new HashMap<String,Object>();
        variables.put("url","/news/finshApply");
        // 启动流程
        ProcessInstance pi= runtimeService.startProcessInstanceByKey(news_apply,variables);
        // 根据流程实例Id查询任务
        Task task=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
        taskService.setAssignee(task.getId(),news.getUserId());
        // 完成任务
        taskService.complete(task.getId());

        // 根据流程实例Id查询任务
        Task taskNext=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
        if(ElUtils.isNotBlank(news.getReview_user())){
            //设置下一审批人
            taskService.setAssignee(taskNext.getId(),news.getReview_user());
        }

        news.setProcessInstanceId(pi.getProcessInstanceId());
        news.setProcessInstanceKey(news_apply);
        return newsMapper.news_add(news);
    }

    @Override
    public News news_by_processInstanceId(String processInstanceId) {
        return newsMapper.news_by_processInstanceId(processInstanceId);
    }

    @Override
    public int news_update(News news) {
        return newsMapper.news_update(news);
    }

    @Override
    public News news_by_id(Integer news_id) {
        return newsMapper.news_by_id(news_id);
    }
}
